package com.hao.msmservice.controller;

import com.hao.commonutils.R;
import com.hao.msmservice.service.MsmService;
import com.hao.msmservice.utils.RandomUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author chenwenhao
 * @version 1.0.0
 * @ClassName MsmController.java
 * @createTime 2020/12/20,12:02
 * @Description
 */
@RestController
@CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phoneNo}")
    public R sendMsm(@PathVariable String phoneNo){
        //从redis中获取验证码，如果有值，直接返回
        String code = redisTemplate.opsForValue().get(phoneNo);
        if (StringUtils.isNotEmpty(code)){
            return R.ok();
        }
        //生成随机四位验证码
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>(16);
        param.put("code",code);
        // 阿里短信功能开通失败，跳过
        //boolean isSend = msmService.sendCode(param,phoneNo);
        boolean isSend = true;
        if (isSend){
            //发送成功，将验证码放入redis，设置有效时间5分钟
            redisTemplate.opsForValue().set(phoneNo,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("短信发送失败");
        }
    }

}
